package com.sprite.framework.context;

import java.io.Serializable;

import com.sprite.framework.security.SecurityDelegator;
import com.sprite.utils.cache.UtilCache;


/**
 * <p>session 上下文，保存当前会话信息</p>
 * <p>线程安全</p>
 * @author Jack
 *
 */
public class SessionContext {
	private static final UtilCache<SessionContext> SESSION_CONTEXT_CACHE = UtilCache.createUtilCache("_SESSION_CONTENTS_");
	
	public static void putSessionContext(String key, SessionContext sessionContext){
		SESSION_CONTEXT_CACHE.put(key, sessionContext);
	}
	
	public static SessionContext getSessionContext(String key){
		return SESSION_CONTEXT_CACHE.get(key);
	}
	
	public static SessionContext instance(){
		return new SessionContext();
	}
	
	private static ThreadLocal<SessionContext> localContext= new ThreadLocal<SessionContext>();
	
	private SecurityDelegator securityMeta;
	
	private String sessionId;
	private String partyId;
	private String groupId;
	private String tenantId;
	private UtilCache<Serializable> contextCache = UtilCache.createUtilCache("cache.sessionContext");
	

	public <T extends Serializable> void put(String key, T object){
		contextCache.put(key, object);
	}
	
	public Serializable get(String key){
		return contextCache.get(key);
	}
	
	public void bind(){
		localContext.set(this);
	}
	
	public void unBind(){
		localContext.remove();
	}
	
	public static SessionContext getSessionContext(){
		return localContext.get();
	}
	
	public static Serializable getFromSession(String key){
		return getSessionContext().get(key);
	}
	
	public SecurityDelegator getSecurityDelegator() {
		return securityMeta;
	}

	public void setSecurityMeta(SecurityDelegator securityMeta) {
		this.securityMeta = securityMeta;
	}
	
	public String getSessionId() {
		return sessionId;
	}

	public void setSessionId(String sessionId) {
		this.sessionId = sessionId;
	}

	public String getPartyId() {
		return partyId;
	}

	public void setPartyId(String partyId) {
		this.partyId = partyId;
	}


	public String getGroupId() {
		return groupId;
	}

	public void setGroupId(String groupId) {
		this.groupId = groupId;
	}
	
	public String getTenantId() {
		return tenantId;
	}

	public void setTenantId(String tenantId) {
		this.tenantId = tenantId;
	}

	/**
	 * 获取当前上下文partyId
	 * @return partyId
	 */
	public static String getPartyIdCurrentSession(){
		SessionContext sessionContext = localContext.get();
		if(sessionContext == null){
			return null;
		}
		return sessionContext.getPartyId();
	}

}
